package com.twobu.twobuinsight.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.twobu.twobuinsight.security.UserContext;
import com.twobu.twobuinsight.security.UserContextHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * MyBatis-Plus 元数据处理器
 * 用于自动填充创建时间、创建人、更新时间、更新人和租户ID等字段
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("开始执行插入填充...");

        // 填充创建时间
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());

        // 填充更新时间
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

        // 获取当前登录用户
        UserContext userContext = UserContextHolder.getUserContext();
        if (userContext != null) {
            // 填充创建人ID
            this.strictInsertFill(metaObject, "createUser", Long.class, userContext.getUserId());
            // 填充更新人ID
            this.strictInsertFill(metaObject, "updateUser", Long.class, userContext.getUserId());
            // 填充租户ID
            this.strictInsertFill(metaObject, "tenantId", Integer.class, userContext.getTenantId());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("开始执行更新填充...");

        // 填充更新时间
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());

        // 获取当前登录用户
        UserContext userContext = UserContextHolder.getUserContext();
        if (userContext != null) {
            // 填充更新人ID
            this.strictUpdateFill(metaObject, "updater", Long.class, userContext.getUserId());
        }
    }
}
